#!/usr/bin/env python

from mcp.server.fastmcp import FastMCP

import requests
from bs4 import BeautifulSoup


mcp = FastMCP(name="MathServer", log_level="ERROR")


BAIKE_URL = 'https://baike.baidu.com'
ITEM_URL = BAIKE_URL + '/item'
header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}


def url2bs(url:str)->BeautifulSoup:
    # get an object of BeautifulSoup from an item name
    resp = requests.get(url, headers=header_dict)
    return BeautifulSoup(resp.content.decode('utf-8'), "lxml")


@mcp.prompt(description="An example of prompt template")
def greeting(name:str) -> str:
    return f"Hello, {name}!"


@mcp.prompt(description="show the result of operation")
def show(value: str) -> str:
    return f"The result is {value}!\n Do you need to show the result in a pretty format?"


@mcp.tool(description="Addition operation")
def add(a: float, b: float) -> float:
    return a + b

@mcp.tool(description="Multiplication operation")
def multiply(a: float, b: float) -> float:
    return a * b

@mcp.tool(description="Search by Baidu")
def search_baidu(query:str) -> str:
    url = url2bs(f'https://www.baidu.com/s?wd={query}')
    title = soup.find('title')
    url = soup.find('link')['href']
    d = {"title": title, "url":url}
    return soup.text


@mcp.tool(description="Search by Baidu-pedia")
def search_baike(query:str) -> str:
    url = ITEM_URL + '/%s' % query
    soup = url2bs(url)
    return soup.text


# @mcp.tool()
# def search_local(file:str, path='.':str) -> str:
#     # loop: search file under path
#     # read file
#     return text


if __name__ == "__main__":
    mcp.run()
